//
//  BaseViewController.m
//  T21info
//
//  Created by 陈区 on 12-10-30.
//  Copyright (c) 2012年 陈区. All rights reserved.
//

#import "BaseViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface BaseViewController () <UIAlertViewDelegate, UIScrollViewDelegate>

@end
//static UIColor *bgColor = nil;
@implementation BaseViewController

//@synthesize tabBarController = m_tabBarController;

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (version >= 7.0) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }

    //    if(!bgColor)
    //    {
    //        bgColor = [[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.png"]] retain];
    //    }
    self.view.backgroundColor = kColor_bg;

    [self setCustomTitleView];
    
    UIImage* image = [UIImage imageNamed:@"back"];
    UIButton* backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:image forState:UIControlStateNormal];
    backBtn.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    [backBtn addTarget:self action:@selector(backBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.leftBarbuttonWidth = image.size.width;
}

- (void)backBtnAction:(UIButton*)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    NSLog(@"didReceiveMemoryWarning self = %@",self);
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
//    if (self.isViewLoaded && !self.view.window)// 是否是正在使用的视图
//    {
//        NSLog(@"self.isViewLoaded && !self.view.window");
//        self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
//    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//是否隐藏标签栏
//- (void)hideTabBarController:(BOOL)isHide
//{
//
//    if (isHide) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:kHideTabBarWhenPushViewController
//                                                            object:nil
//                                                          userInfo:nil];
//    }
//    else {
//        [[NSNotificationCenter defaultCenter] postNotificationName:kShowTabBarWhenPopViewController
//                                                            object:nil
//                                                          userInfo:nil];
//    }
//}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if ([self.parentViewController isKindOfClass:[UINavigationController class]]) {
        if (self.hidesBottomBarWhenPushed) {
//            [self hideTabBarController:YES];
        }
        else {
//            [self hideTabBarController:NO];
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if ([self.parentViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navCtl = (UINavigationController*)self.parentViewController;
        if (self.hidesBottomBarWhenPushed && navCtl.visibleViewController && !navCtl.visibleViewController.hidesBottomBarWhenPushed) {
//            [self hideTabBarController:NO];
        }
    }
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
}

- (void)presentModalViewController:(UIViewController*)modalViewController animated:(BOOL)animated
{

//    [self hideTabBarController:YES];

    if ([super respondsToSelector:@selector(presentModalViewController:animated:)]) {
        [super presentModalViewController:modalViewController animated:animated];
    }
    else {
        [super presentViewController:modalViewController animated:animated completion:nil];
    }
}

- (void)dismissModalViewControllerAnimated:(BOOL)animated
{

    if ([super respondsToSelector:@selector(dismissModalViewControllerAnimated:)]) {
        [super dismissModalViewControllerAnimated:animated];
    }
    else {
        [super dismissViewControllerAnimated:animated completion:nil];
    }
}

//- (void)setTitle:(NSString*)title
//{
//    [self setCustomTitleView];
//    m_lbTitle.text = title;
//}

- (void)setLeftBarbuttonWidth:(CGFloat)leftBarbuttonWidth
{
    _leftBarbuttonWidth = leftBarbuttonWidth;
    [self setCustomTitleView];
}

- (void)setCustomTitleView
{
    if (!self.navigationItem.titleView || [self.navigationItem.titleView isEqual:m_titleView]) {//防止把子类中自定义的titleView改到
        if (m_titleView == nil) {
            m_titleView = [[UIView alloc] init];
            m_titleView.backgroundColor = [UIColor clearColor];
            
            m_lbTitle = [[UILabel alloc] init];
            m_lbTitle.font = [UIFont fontWithName:kFontNameLight size:16];
            m_lbTitle.textColor = KBlackColor;
            m_lbTitle.textAlignment = NSTextAlignmentCenter;
            m_lbTitle.backgroundColor = [UIColor clearColor];
            [m_titleView addSubview:m_lbTitle];
        }
        CGFloat width = [self getTitleViewWidth];
        m_titleView.frame = CGRectMake(0, 0, width, 40);//在iOS11以前可能失效，宽度取决于左右两边的按钮
        m_lbTitle.frame = CGRectMake(0, 0, width, 40);//两层解决iOS10以前宽度失效问题
        self.navigationItem.titleView = m_titleView;
    }
}

- (CGFloat)getTitleViewWidth
{
    CGFloat leftPadding;
    if (KScreenWidth > 375.0) {//默认情况下，在320、375宽度的屏幕上，第一个按钮距离屏幕左边界的宽度是16，在414第一个按钮距离屏幕左边界的宽度是20。
        leftPadding = 20;
    }else {
        leftPadding = 16;
    }
    CGFloat itemPadding;
    if (@available(iOS 11.0, *)) {//在iOS11之前，titleview和barbutton之间的间距是6p，在iOS11上titleview和barbutton之间无间距
        itemPadding = 0;
    }else {
        itemPadding = 6;
    }
    CGFloat width = ScreenWidth - (leftPadding + itemPadding + self.leftBarbuttonWidth) * 2;
    return width;
}

//左侧按钮
- (void)onNavigationLeftButtonClicked:(UIButton*)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

//右侧按钮
- (void)onNavigationRightButtonClicked:(UIButton*)sender
{
}

//右侧按钮旁边的按钮点击
- (void)onNavigationRightLeftButtonClicked:(UIButton*)sender
{
}

//中间按钮
- (void)onNavigationMiddleButtonClicked:(UISegmentedControl*)sender
{
}

//设置导航条背景颜色
- (void)setNavigationBarBackgroudImage:(NSString*)imageName withIos7name:(NSString*)imageName2
{
    UIImage* bgImage;

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
        bgImage = [UIImage imageNamed:imageName2];
    }
    else {
        bgImage = [UIImage imageNamed:imageName];
    }

    [self.navigationController.navigationBar setBackgroundImage:bgImage forBarMetrics:UIBarMetricsDefault];
}

//导航栏左侧显示返回按钮
- (void)showCustomNavigationBackButton
{
    //导航栏的左边按钮
    UIImage* image = [UIImage imageNamed:@"icon_back"];
    CGFloat wid = image.size.width + 10;
    UIButton* leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, wid, image.size.height)];
//    [leftButton setBackgroundImage:image forState:UIControlStateNormal];
//    [leftButton setBackgroundImage:image forState:UIControlStateHighlighted];
    [leftButton setImage:image forState:UIControlStateNormal];
    [leftButton setImage:image forState:UIControlStateHighlighted];

    [leftButton addTarget:self action:@selector(onNavigationLeftButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButton = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    self.leftBarbuttonWidth = image.size.width + 10;
}

//导航栏左侧显示绿色返回按钮
- (void)showCustomNavigationGreedBackButton:(NSString*)imageNorName withPreImage:(NSString*)imagePreName
{
    //    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 51, 41)];
    UIImage* image = [UIImage imageNamed:imageNorName];
    UIButton* leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
    [leftButton setBackgroundImage:[UIImage imageNamed:imageNorName] forState:UIControlStateNormal];
    [leftButton setBackgroundImage:[UIImage imageNamed:imagePreName] forState:UIControlStateHighlighted];
    [leftButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [leftButton addTarget:self action:@selector(onNavigationLeftButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.leftBarbuttonWidth = image.size.width;
}

//显示导航栏左侧的按钮
- (void)showCustomNavigationLeftButtonWithTitle:(NSString*)aTitle image:(UIImage*)aImage hightlightImage:(UIImage*)hImage
{
    //导航栏的左边按钮
    UIButton* leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 40)];
    //    leftButton.backgroundColor = [UIColor redColor];
    UIImageView* iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, (40 - aImage.size.height) / 2, aImage.size.width, aImage.size.height)];
    [leftButton addSubview:iconImageView];

    if (aTitle) {
        [leftButton setTitle:aTitle forState:UIControlStateNormal];
        [leftButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        leftButton.titleLabel.font = [UIFont fontWithName:kFontNameLight size:14];
    }
    [iconImageView setImage:aImage];
    //    [leftButton setBackgroundImage:aImage forState:UIControlStateNormal];
    if (hImage) {
        [iconImageView setImage:aImage];
        //        [leftButton setBackgroundImage:hImage forState:UIControlStateHighlighted];
    }

    [leftButton addTarget:self action:@selector(onNavigationLeftButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.leftBarbuttonWidth = leftButton.frame.size.width;
}

//显示导航栏右边的按钮
- (void)showCustomNavigationRightButtonWithTitle:(NSString*)aTitle image:(UIImage*)aImage hightlightImage:(UIImage*)hImage
{
    [self showCustomNavigationRightButtonWithTitle:aTitle image:aImage hightlightImage:hImage color:nil];
}

//显示导航栏右边两个按钮
- (void)showCustomNavigationRightButtonWithimage:(UIImage*)aImage hightlightImage:(UIImage*)hImage image2:(UIImage*)aImage2 hightlightImage2:(UIImage*)hImage2
{
    
    //导航栏的右边按钮
    UIButton* rightButton = [[UIButton alloc] init];
    //导航栏的左边按钮
    UIButton* rigLeftButton = [[UIButton alloc] init];
    
    [rigLeftButton setBackgroundImage:aImage forState:UIControlStateNormal];
    if (hImage) {
        [rigLeftButton setBackgroundImage:hImage forState:UIControlStateHighlighted];
    }
    [rigLeftButton setBackgroundImage:aImage2 forState:UIControlStateNormal];
    if (hImage) {
        [rigLeftButton setBackgroundImage:hImage2 forState:UIControlStateHighlighted];
    }
    

    UIView *rightView = [[UIView alloc] init];
    rightView.frame = CGRectMake(0.0, 0.0, 80.0, 47.0);
    [rightView addSubview:rightButton];
    [rightView addSubview:rigLeftButton];
    [rightButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(rightView).mas_offset(-15);
        make.centerY.equalTo(rightView);
        make.width.mas_equalTo(aImage.size.width);
        make.height.mas_equalTo(aImage.size.height);
    }];
    [rigLeftButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(rightButton.mas_left).mas_offset(-10);
        make.centerY.equalTo(rightView);
        make.width.mas_equalTo(aImage2.size.width);
        make.height.mas_equalTo(aImage2.size.height);
    }];
    
    [rightButton addTarget:self action:@selector(onNavigationRightButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [rigLeftButton addTarget:self action:@selector(onNavigationRightLeftButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightView];
}


- (void)showCustomNavigationRightButtonWithTitle:(NSString*)aTitle image:(UIImage*)aImage hightlightImage:(UIImage*)hImage color:(UIColor*)color
{
    //导航栏的左边按钮
    UIButton* rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, aImage.size.width, aImage.size.height)];
    
    if (aTitle) {
        
        [rightButton setTitle:aTitle forState:UIControlStateNormal];
        rightButton.titleLabel.font = [UIFont fontWithName:kFontNameLight size:14];
        
        NSDictionary* attribute = @{ NSFontAttributeName : rightButton.titleLabel.font };
        CGSize textSize = [aTitle boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 0) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
        
        rightButton.frame = CGRectMake(0, 0, textSize.width, 41);
        [rightButton setTitleColor: color ? color : KBlackColor forState:UIControlStateNormal];
        [rightButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -13)];
    }
    
    [rightButton setBackgroundImage:aImage forState:UIControlStateNormal];
    if (hImage) {
        [rightButton setBackgroundImage:hImage forState:UIControlStateHighlighted];
    }
    
    [rightButton addTarget:self action:@selector(onNavigationRightButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
}

//显示两个导航栏右边的按钮
- (void)showTwoRightButtonWithTitle:(NSString*)aTitle1 image1:(UIImage*)aImage1 hightlightImage1:(UIImage*)hImage1
                             title2:(NSString*)aTitle2
                             image2:(UIImage*)aImage2
                   hightlightImage1:(UIImage*)hImage2
{
    UIView* buttonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, aImage2.size.width + aImage1.size.width + 20, aImage2.size.height)];
    UIButton* rightButton1 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, aImage1.size.width, aImage1.size.height)];
    UIButton* rightButton2 = [[UIButton alloc] initWithFrame:CGRectMake(aImage1.size.width + 20, 0, aImage2.size.width, aImage2.size.height)];
    [buttonView addSubview:rightButton1];
    [buttonView addSubview:rightButton2];
    if (aTitle1) {
        [rightButton1 setTitle:aTitle1 forState:UIControlStateNormal];
        [rightButton1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        rightButton1.titleLabel.font = [UIFont fontWithName:kFontNameLight size:17];
        [rightButton1 setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -13)];
    }
    if (aTitle2) {
        [rightButton2 setTitle:aTitle1 forState:UIControlStateNormal];
        [rightButton2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        rightButton2.titleLabel.font = [UIFont fontWithName:kFontNameLight size:17];
        [rightButton2 setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -13)];
    }

    [rightButton1 setBackgroundImage:aImage1 forState:UIControlStateNormal];
    [rightButton2 setBackgroundImage:aImage2 forState:UIControlStateNormal];

    if (hImage1) {
        [rightButton1 setBackgroundImage:hImage1 forState:UIControlStateHighlighted];
    }
    if (hImage2) {
        [rightButton2 setBackgroundImage:hImage2 forState:UIControlStateHighlighted];
    }

    [rightButton1 addTarget:self action:@selector(onNavigationRightButton1Clicked:) forControlEvents:UIControlEventTouchUpInside];
    [rightButton2 addTarget:self action:@selector(onNavigationRightButton2Clicked:) forControlEvents:UIControlEventTouchUpInside];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:buttonView];
}

//显示导航栏下边带文字的按钮
- (void)showCustomNavigationRightButtonWithDownTitle:(NSString*)aTitle image:(UIImage*)aImage hightlightImage:(UIImage*)hImage
{
    //导航栏的右边按钮
    UIButton* rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 51, 41)];

    UIImageView* bg = [[UIImageView alloc] initWithFrame:CGRectMake(21 + 10, 5, 18, 17)];
    bg.image = aImage;
    [rightButton addSubview:bg];

    if (aTitle) {
        UILabel* title = [[UILabel alloc] initWithFrame:CGRectMake(10 + 10, bg.frame.origin.y + bg.frame.size.height + 4, 36, 15)];
        title.textColor = [UIColor whiteColor];
        title.font = [UIFont fontWithName:kFontNameLight size:12.0f];
        title.textAlignment = NSTextAlignmentLeft;
        title.text = aTitle;
        [rightButton addSubview:title];
    }

    [rightButton addTarget:self action:@selector(onNavigationRightButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
}

//显示导航栏下边带文字的按钮
- (void)showCustomNavigationLeftButtonWithDownTitle:(NSString*)aTitle image:(UIImage*)aImage hightlightImage:(UIImage*)hImage
{
    //导航栏的左边按钮
    UIButton* leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 51, 41)];

    UIImageView* bg = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 18, 17)];
    bg.image = aImage;
    [leftButton addSubview:bg];

    if (aTitle) {
        UILabel* title = [[UILabel alloc] initWithFrame:CGRectMake(-5, bg.frame.origin.y + bg.frame.size.height + 4, 36, 15)];
        title.textColor = [UIColor whiteColor];
        title.font = [UIFont fontWithName:kFontNameLight size:12.0f];
        title.textAlignment = NSTextAlignmentLeft;
        title.text = aTitle;
        [leftButton addSubview:title];

    }

    [leftButton addTarget:self action:@selector(onNavigationLeftButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.leftBarbuttonWidth = aImage.size.width;
}

//显示导航栏右边的按钮（可设置颜色）
- (void)showCustomNavigationRightButtonWithColorTitle:(NSString*)aTitle image:(UIImage*)aImage hightlightImage:(UIImage*)hImage titleColor:(UIColor*)color
{
    //导航栏的左边按钮
    UIButton* rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35, 44)];

    if (aTitle) {
        CGSize size = STRING_SIZE_FONT(1000, aTitle, 14);
        rightButton.frame = CGRectMake(0, 0, size.width, 44);
        [rightButton setTitle:aTitle forState:UIControlStateNormal];
        [rightButton setTitleColor:color forState:UIControlStateNormal];
        rightButton.titleLabel.font = [UIFont fontWithName:kFontNameLight size:14];
        //        [rightButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -14)];
    }
    else {
        rightButton.frame = CGRectMake(0, 0, aImage.size.width, aImage.size.height);
    }

    [rightButton setBackgroundImage:aImage forState:UIControlStateNormal];
    if (hImage) {
        [rightButton setBackgroundImage:hImage forState:UIControlStateHighlighted];
    }

    [rightButton addTarget:self action:@selector(onNavigationRightButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
}

//显示导航栏左边的按钮（可设置颜色）
- (void)showCustomNavigationLeftButtonWithColorTitle:(NSString*)aTitle image:(UIImage*)aImage hightlightImage:(UIImage*)hImage titleColor:(UIColor*)color
{
    //导航栏的左边按钮

    UIButton* LeftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 44)];

    if (aTitle) {
        [LeftButton setTitle:aTitle forState:UIControlStateNormal];
        [LeftButton setTitleColor:color forState:UIControlStateNormal];
        LeftButton.titleLabel.font = [UIFont fontWithName:kFontNameLight size:14];
        LeftButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; //设置文字位置，现设为居左，默认的是居中
    }

    [LeftButton setBackgroundImage:aImage forState:UIControlStateNormal];
    if (hImage) {
        [LeftButton setBackgroundImage:hImage forState:UIControlStateHighlighted];
    }

    [LeftButton addTarget:self action:@selector(onNavigationLeftButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:LeftButton];
    self.leftBarbuttonWidth = LeftButton.frame.size.width;
}

//隐藏右边导航按钮
- (void)hideNavigationRightButtonWithColorTitle
{
    self.navigationItem.rightBarButtonItem = nil;
}

- (void)judgeCameraAuthorizationStatus
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {

        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus != AVAuthorizationStatusAuthorized) {
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"请在iphone的设置-隐私-相机选项中,允许%@访问你的相机",@"药动销"] message:
                                                                                                                                     nil
                                                           delegate:nil
                                                  cancelButtonTitle:NSLocalizedString(@"确定", @"")
                                                  otherButtonTitles:nil];
            [alert show];
        }
    }
}

#pragma mark -
#pragma mark 从屏幕上载取图片
- (UIImage*)saveScreenShotImage:(UIView*)aview
{

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(CGRectGetWidth(self.view.bounds), CGRectGetHeight(aview.bounds)), NO, 1.0); //NO，YES 控制是否透明
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    // 生成后的image

    return image;
}

#pragma mark -
#pragma mark 图片缓存存取与读取
- (NSData*)saveServiceImage:(NSURL*)url
{

    NSArray* fileArray = [[url absoluteString] componentsSeparatedByString:@"/"];
    NSString* fileName = [fileArray objectAtIndex:[fileArray count] - 1];

    //取出document路径
    NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    NSFileManager* fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", filePath, fileName]]) {

        //#ifdef DEBUG
        //        NSLog(@"读取成功");
        //#endif

        NSData* data = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", filePath, fileName]];
        return data;
    }
    else {

        NSData* data = [NSData dataWithContentsOfURL:url];

        //保存数据
        if ([data writeToFile:[NSString stringWithFormat:@"%@/%@", filePath, fileName] atomically:YES]) {

#ifdef DEBUG
            NSLog(@"写入成功");
#endif
        }

        return data;
    }
}

- (NSData*)saveServiceImage:(NSURL*)url imageView:(UIImageView*)imageView
{
    NSArray* fileArray = [[url absoluteString] componentsSeparatedByString:@"/"];
    NSString* fileName = [fileArray objectAtIndex:[fileArray count] - 1];

    //取出document路径
    NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    NSFileManager* fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", filePath, fileName]]) {

        //#ifdef DEBUG
        //        NSLog(@"读取成功");
        //#endif

        NSData* data = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", filePath, fileName]];

        [imageView setImage:[UIImage imageWithData:data]];

        return data;
    }
    else {

        NSData* data = [NSData dataWithContentsOfURL:url];
        //保存数据
        if ([data writeToFile:[NSString stringWithFormat:@"%@/%@", filePath, fileName] atomically:YES]) {

#ifdef DEBUG
            NSLog(@"写入成功");
#endif
            [imageView setImage:[UIImage imageWithData:data]];
        }

        return data;
    }
}

#pragma mark -
#pragma mark 字体的宽度和高度
- (float)heightForString:(NSString*)value fontSize:(float)fontSize andWidth:(float)width
{
    CGSize sizeToFit = [value sizeWithFont:[UIFont fontWithName:kFontNameLight size:fontSize] constrainedToSize:CGSizeMake(width, CGFLOAT_MAX) lineBreakMode:NSLineBreakByCharWrapping]; //此处的换行类型（lineBreakMode）可根据自己的实际情况进行设置
    return sizeToFit.height;
}

#pragma mark 时间转换
#pragma mark -
- (NSString*)showDate:(NSString*)dateStr
{
    //输入时间
    NSDate* inputdate = [NSDate dateWithTimeIntervalSince1970:[dateStr doubleValue] / 1000];
    //    NSLog(@"%@",inputdate);

    NSDateFormatter* inputFormatter = [[NSDateFormatter alloc] init];
    inputFormatter.timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Beijing"];
    //    NSString*string = @"20151117121821";
    //    [inputFormatter setDateFormat:@"yyyyMMddHHmmss"];
    //    NSDate *inputdate=[inputFormatter dateFromString:string];
    //    NSLog(@"%@",inputdate);

    [inputFormatter setDateFormat:@"yyyy"];
    NSString* nowyear = [inputFormatter stringFromDate:[NSDate date]];
    NSString* inputyear = [inputFormatter stringFromDate:inputdate];
    int yearDistance = [nowyear intValue] - [inputyear intValue];
    //    NSLog(@"%@-%@=%d", nowyear,inputyear,yearDistance);

    [inputFormatter setDateFormat:@"MM"];
    NSString* nowmonth = [inputFormatter stringFromDate:[NSDate date]];
    NSString* inputmonth = [inputFormatter stringFromDate:inputdate];
    int monthDistance = [nowmonth intValue] - [inputmonth intValue];
    //    NSLog(@"%@-%@=%d", nowmonth,inputmonth,monthDistance);

    [inputFormatter setDateFormat:@"dd"];
    NSString* nowday = [inputFormatter stringFromDate:[NSDate date]];
    NSString* inputday = [inputFormatter stringFromDate:inputdate];
    int dayDistance = [nowday intValue] - [inputday intValue];
    //    NSLog(@"%@-%@=%d", nowday,inputday,dayDistance);

    NSString* date = nil;
    if (yearDistance == 0 && monthDistance == 0 && dayDistance == 0) {

        [inputFormatter setDateFormat:@"HH:mm"];
        date = [inputFormatter stringFromDate:inputdate];
    }
    else if (yearDistance == 0 && monthDistance == 0 && dayDistance == 1) {

        [inputFormatter setDateFormat:@"HH:mm"];
        date = [NSString stringWithFormat:@"昨天 %@", [inputFormatter stringFromDate:inputdate]];
    }
    //    else if (yearDistance==0 && monthDistance==0 && dayDistance<=7){
    //
    //        date=[NSString stringWithFormat:@"%@",[self weekdayStringFromDate:inputdate]];
    //
    //    }
    else {

        [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        date = [inputFormatter stringFromDate:inputdate];
    }
    //    NSLog(@"%@",date);
    return date;
}
- (NSString*)weekdayStringFromDate:(NSDate*)inputDate
{

    NSArray* weekdays = [NSArray arrayWithObjects:[NSNull null], @"星期日", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六", nil];

    NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSTimeZone* timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Beijing"];

    [calendar setTimeZone:timeZone];

    NSCalendarUnit calendarUnit = NSWeekdayCalendarUnit;

    NSDateComponents* theComponents = [calendar components:calendarUnit fromDate:inputDate];

    return [weekdays objectAtIndex:theComponents.weekday];
}


- (void)onHideDefaultImage:(UIView*)view
{
    for (UIView* aview in view.subviews) {
        if (aview.tag == 999999) {
            [aview removeFromSuperview];
        }
    }
}

- (NSString*)onChangeStrToDate:(NSString*)dateStr
{
    //
    //    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //    NSDate *date = [formatter dateFromString:dateStr];
    //
    //    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
    //
    //    [formatter release];
    return dateStr;
}

#pragma mark - 图片操作
/**
 *  显示图片
 *
 *  @param picArray 图片组
 *  @param index    滚动到当前图
 */
- (void)showMorePic:(NSArray*)picArray indexPic:(NSInteger)index
{
    CGSize size = [[UIScreen mainScreen] bounds].size;
    UIView* bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];

    [UIView animateWithDuration:0.5 animations:^{
        bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.9];

    }
        completion:^(BOOL finished) {
            UITapGestureRecognizer* closeTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onCloseTapAction:)];
            [bgView addGestureRecognizer:closeTap];
        }];

    UIScrollView* picScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(bgView.bounds), CGRectGetHeight(bgView.bounds))];
    picScrollView.showsHorizontalScrollIndicator = NO;
    picScrollView.showsVerticalScrollIndicator = NO;
    picScrollView.pagingEnabled = YES;
    picScrollView.contentSize = CGSizeMake([picArray count] * CGRectGetWidth(bgView.bounds), 0);
    picScrollView.contentOffset = CGPointMake(index * CGRectGetWidth(picScrollView.bounds), 0);
    [bgView addSubview:picScrollView];

    for (int i = 0; i < [picArray count]; i++) {
        UIImageView* aImageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * CGRectGetWidth(picScrollView.bounds), 0, CGRectGetWidth(picScrollView.bounds), CGRectGetHeight(picScrollView.bounds))];
        aImageView.contentMode = UIViewContentModeScaleAspectFit;
//        [aImageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", kImageServerRootURL, [picArray objectAtIndex:i]]] placeholderImage:[UIImage imageNamed:@"erweima"] options:SDWebImageCacheMemoryOnly];
        [picScrollView addSubview:aImageView];

    }

    [[[UIApplication sharedApplication] keyWindow] addSubview:bgView];
}

//继承动画
- (void)showMorePic:(NSArray*)picArray indexPic:(NSInteger)index ImageView:(UIImageView*)ImageView
{

    CGSize size = [[UIScreen mainScreen] bounds].size;
    UIView* bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];

    [UIView animateWithDuration:0.5 animations:^{
        bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.9];

    }
        completion:^(BOOL finished) {
            UITapGestureRecognizer* closeTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onCloseTapAction:)];
            [bgView addGestureRecognizer:closeTap];
        }];

    UIScrollView* picScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(bgView.bounds), CGRectGetHeight(bgView.bounds))];
    picScrollView.showsHorizontalScrollIndicator = NO;
    picScrollView.showsVerticalScrollIndicator = NO;
    picScrollView.pagingEnabled = YES;
    picScrollView.contentSize = CGSizeMake([picArray count] * CGRectGetWidth(bgView.bounds), 0);
    picScrollView.contentOffset = CGPointMake(index * CGRectGetWidth(picScrollView.bounds), 0);
    [bgView addSubview:picScrollView];

    //    //坐标转化
    //    CGPoint point = [ImageView convertPoint:ImageView.bounds.origin toView:picScrollView];
    //
    //    UIImageView *aImageView = [[UIImageView alloc] initWithFrame:CGRectMake(index*CGRectGetWidth(picScrollView.bounds), 0, 60, 60)];
    //    aImageView.contentMode = UIViewContentModeScaleAspectFit;
    //    [aImageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",kImageServerRootURL,[picArray objectAtIndex:index]]] placeholderImage:[UIImage imageNamed:@"erweima"] options:SDWebImageCacheMemoryOnly];
    //    [picScrollView addSubview:aImageView];
    //    aImageView.alpha = 0;
    //    [aImageView release];
    //
    //    aImageView.center = point;
    //
    //
    //    [UIView animateWithDuration:0.5 animations:^{
    //        aImageView.frame = CGRectMake(index*CGRectGetWidth(picScrollView.bounds), 0, CGRectGetWidth(picScrollView.bounds), CGRectGetHeight(picScrollView.bounds));
    //        aImageView.alpha = 1;
    //    }];

    for (int i = 0; i < [picArray count]; i++) {
        UIScrollView* scaleScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(i * CGRectGetWidth(picScrollView.bounds), 0, CGRectGetWidth(picScrollView.bounds), CGRectGetHeight(picScrollView.bounds))];
        scaleScrollView.tag = 100000;
        scaleScrollView.minimumZoomScale = 1;
        scaleScrollView.maximumZoomScale = 5;
        scaleScrollView.delegate = self;
        [picScrollView addSubview:scaleScrollView];
        scaleScrollView.contentSize = CGSizeMake(CGRectGetWidth(picScrollView.bounds), CGRectGetHeight(picScrollView.bounds));

        UIImageView* aImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(picScrollView.bounds), CGRectGetHeight(picScrollView.bounds))];
        aImageView.contentMode = UIViewContentModeScaleAspectFit;
//        [aImageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", kImageServerRootURL, [picArray objectAtIndex:i]]] placeholderImage:[UIImage imageNamed:@"erweima"] options:SDWebImageCacheMemoryOnly];
        [scaleScrollView addSubview:aImageView];

        //当前页不重复加载图片
        if (i == index) {
            aImageView.frame = CGRectMake((CGRectGetWidth(scaleScrollView.bounds) - 90) / 2, (CGRectGetHeight(scaleScrollView.bounds) - 90) / 2, 90, 90);

            //动态图片显示
            [UIView animateWithDuration:0.3 animations:^{
                aImageView.frame = CGRectMake(0, 0, CGRectGetWidth(scaleScrollView.bounds), CGRectGetHeight(scaleScrollView.bounds));
            }
                completion:^(BOOL finished){

                }];
        }
    }


    [[[UIApplication sharedApplication] keyWindow] addSubview:bgView];
}

- (UIView*)viewForZoomingInScrollView:(UIScrollView*)scrollView
{
    if (scrollView.tag == 100000) {
        for (UIImageView* aImageView in scrollView.subviews) {
            if ([aImageView isKindOfClass:[UIImageView class]]) {
                return aImageView;
                break;
            }
        }
    }
    return nil;
}

- (void)onCloseTapAction:(UIGestureRecognizer*)recognizer
{
    [[recognizer view] removeFromSuperview];
}

//数值转换
-(NSString *)onChangeValueType:(id)objStr
{
    if ([objStr isEqual:[NSNull null]])
    {
        return @"";
    }
    else if ([objStr isKindOfClass:[NSNumber class]])
    {
        return [objStr stringValue];
    }
    else
    {
        return objStr;
    }
}

/**
 *  正则表达式
 *
 *  @param textString 输入字符串
 *  @param code       正则表达式
 *
 *  @return YES匹配  NO不匹配
 */
-(BOOL)isExpressCode:(NSString *)textString expressStr:(NSString *)code
{
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",code];
    return [numberPre evaluateWithObject:textString];
}

/**
 字典转json
 */
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

/**
 数组转json
 */
- (NSArray *)arrayWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    NSMutableString *responseString = [NSMutableString stringWithString:jsonString];
    NSString *character = nil;
    for (int i = 0; i < responseString.length; i ++) {
        character = [responseString substringWithRange:NSMakeRange(i, 1)];
        if ([character isEqualToString:@"\\"])
            [responseString deleteCharactersInRange:NSMakeRange(i, 1)];
    }
    NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err = nil;
    NSArray *arr = [NSJSONSerialization JSONObjectWithData:jsonData
                                                   options:NSJSONReadingMutableContainers
                                                     error:&err];
    return arr;
}


/**
 数值转换
 */
-(NSInteger)onChangeIntegerValueType:(id)objStr
{
    if ([objStr isEqual:[NSNull null]]) {
        return 0;
        
    } else if ([objStr isKindOfClass:[NSNumber class]]) {
        return [objStr integerValue];
        
    } else if ([objStr isKindOfClass:[NSString class]]) {
        return [objStr integerValue];
        
    } else{
        return (NSInteger)objStr;
    }
}

/**
 *  上传图片自动转了90度
 */
- (UIImage *)fixOrientation:(UIImage *)aImage
{
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

-(void)imageView:(UIImageView*)imageView setImageUrl:(NSURL*)url defaultImage:(UIImage*)image
{
    [imageView setImageWithURL:url placeholderImage:image options:SDWebImageLowPriority];
}


- (NSString *)titleString
{
    if (!_titleString) {
        _titleString = @"";
    }
    return _titleString;
}


- (NSString *)objName
{
    if (!_objName) {
        _objName = @"-";
    }
    return _objName;
}

@end
